package com.bbs.controller;

import com.bbs.security.AuthProperties;
import com.bbs.pojo.Result;
import com.bbs.service.AuthenticationService;
import com.bbs.service.dto.CredentialDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api")
public class AuthenticationController {
    @Autowired
    AuthenticationService authenticationService;
    @Autowired
    UserDetailsService userDetailService;

    /**
     * 登录认证
     * @param credentialDto
     * @param response
     * @return
     */
    @PostMapping("/auth/login")
    public Result<Object> authenticate(@RequestBody CredentialDto credentialDto, HttpServletResponse response){
        String token = authenticationService.authenticate(credentialDto);

        if(token != null){
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setHttpOnly(false);
            cookie.setPath("/");
            Boolean rememberMe = credentialDto.getRememberMe();
            if(rememberMe != null && rememberMe){
                cookie.setMaxAge((int)AuthProperties.rememberMeValidTime);
            }
            response.addCookie(cookie);

            return Result.succeed();
        }else{
            return Result.fail();
        }
    }

//    @PostMapping("/auth/logout")
//    public Result<Object> logout(HttpServletResponse response){
//        Cookie cookie = new Cookie("TOKEN", "");
//        cookie.setHttpOnly(true);
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        return Result.succeed();
//    }
}
